package com.wujilee.wujileenetty.demos.web.netty.heima;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;

/**
 * @author liwuji
 * @date 2024/8/6
 * @desc netty 客户端基本案例
 **/
public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 客户端开启连接后调用该方法
                        ch.pipeline().addLast(new StringEncoder());
                        System.out.println("客户端连接成功");
                    }

                }).connect(new InetSocketAddress("127.0.0.1", 5672))
                .sync().channel();


    }

    public static void hello() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 客户端开启连接后调用该方法
                        ch.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress("127.0.0.1", 5672))
                .sync();

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                channel.writeAndFlush("hello world");
                // 该方法是异步的
                channel.close();
                ChannelFuture channelFuture1 = channel.closeFuture();
                // 该方法是阻塞的会等clos方法执行完毕后才继续执行
                channelFuture1.sync();

                // 关闭之后的处理
                System.out.println("；连接已关闭");
                 // 二选一关闭之后的处理
                channelFuture1.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        System.out.println("；连接已关闭");
                        // 优雅关闭
                        group.shutdownGracefully();
                    }
                });


            }
        });

    }
}
